package com.coffee.core.util;

import com.coffee.core.entity.Page;

import java.util.ArrayList;
import java.util.List;

/**
 * 手动分页工具
 *
 * @author Xulg
 * Created in 2019-05-04 14:13
 */
public class ManualPageUtils {

    /**
     * 手动对集合分页
     *
     * @param currentPage 当前页
     * @param pageSize    每页个数
     * @param list        the data list
     * @return the page list
     */
    public static <T> List<T> manualPage(int currentPage, int pageSize, List<T> list) {
        if (list == null || list.isEmpty()) {
            return new ArrayList<>(0);
        }
        if (currentPage <= 0) {
            currentPage = 1;
        }
        if (pageSize <= 0) {
            pageSize = 10;
        }
        if (pageSize >= Integer.MAX_VALUE) {
            return list;
        }
        // 总记录数
        int allCount = list.size();
        // 总页数
        int pageCount = (allCount + pageSize - 1) / pageSize;
        if (currentPage > pageCount) {
            // 查看的页码大于总页数
            return new ArrayList<>(0);
        }
        int start = (currentPage - 1) * pageSize;
        int end = currentPage * pageSize;
        if (end >= allCount) {
            end = allCount;
        }
        return new ArrayList<>(list.subList(start, end));
    }

    /**
     * 手动对集合分页
     *
     * @param currentPage 当前页
     * @param pageSize    每页个数
     * @param list        the data list
     * @return the page data
     */
    public static <T> Page<T> page(int currentPage, int pageSize, List<T> list) {
        if (list == null || list.isEmpty()) {
            return Page.emptyPageData(currentPage, pageSize);
        }
        Page<T> page = new Page<>(currentPage, pageSize);
        page.setData(manualPage(currentPage, pageSize, list));
        page.setAmount(list.size());
        return page;
    }
}
